<?php
namespace admin;

use models\BaseDoo;

class Advert extends Admin{
    protected $dataBase;
    protected $dataGG = [];
    public function __construct()
    {
        $this->dataBase = new BaseDoo();
        $this->dataGG = [1=>'顶部广告位',2=>'中间广告位',3=>'底部广告位'];
        $this->assign('lh_php','LH_PHP');
        parent::__construct();
    }

    //列表展示
    public function index(){
        $this->assign('title','广告列表');
        $field = '*';
        $advert_list = $this->dataBase->select('advert',$field,['ORDER'=>['order'=>'DESC']]);
        $this->assign('advert_list',$advert_list);
        $this->display('advert/index');
    }


    //添加客户页面显示
    public function add(){
        $this->assign('dataGG',$this->dataGG);
        $this->display('advert/add');
    }


    //添加客户操作
    public function add_do(){
        $this->dataBase->insert('advert',$_POST);
        if($this->dataBase->id()){
            return show(1,'广告添加成功',[]);
        }else{
            return show(-1,'广告添加失败',[]);
        }
    }

    //广告位修改页面
    public function edit(int $id){
        $find = $this->dataBase->get('advert','*',['id' => $id]);
        $this->assign('dataGG',$this->dataGG);
        $this->assign($find);
        $this->display('advert/edit');
    }



    //进行广告位修改
    public function update(){
        $id = $_POST['id'];
        unset($_POST['id']);
        $pic_old = $this->dataBase->get('advert','pic',['id'=>$id]);
        $pic = trim($_POST['pic']);
        //如果真的传递过来了图片，就进行删除操作
        unset($_POST['pic']);
        if($pic_old != $pic){
            $pic_path = TEMPDIR.$pic_old;
            if(file_exists($pic_path)){
                @unlink($pic_path);
            }
            $_POST['pic'] = $pic;
        }
        $update = $this->dataBase->update('advert',$_POST,['id'=>$id]);
        if($update){
            return show(1,'修改成功',[]);
        }else{
            return show(-1,'修改失败');
        }
    }

    //进行删除操作
    public function delete($id){
        $pic_old = $this->dataBase->get('advert','pic',['id'=>$id]);
        if($this->dataBase->delete('advert',['id'=>$id])){
            $pic_path = TEMPDIR.$pic_old;
            if(file_exists($pic_path)){
                @unlink($pic_path);
            }
            return show(1,'删除成功',[]);
        }else{
            return show(0,'删除失败',[]);
        }
    }


    //上传图片
    public function upload(){
        $upFile = $_FILES['file'];
        $res = uploadToLocal($upFile,'ad');
        return $res;
    }









}